﻿using Net.RequestHandle;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace MeetFuture.MRC.Commands
{
    public interface ICommandSupplemental
    {
        List<KeyValue> Waitings { get; set; }
        void PublishMessage(clsAGVInfo agvinfo, string cmd);
    }
    public class KeyValue
    {
        public string _key { get; set; }
        public string _value { get; set; }
        public KeyValue(string key, string value)
        {
            _key = key;
            _value = value;
        }
    }
    public class BasicCommand
    {
        public string SendSync(ICommandSupplemental supplemental, clsAGVInfo agvinfo, string cmd)
        {
            if (supplemental == null || supplemental.Waitings == null || supplemental.Waitings.Count <= 0)
            {
                throw new Exception("The supplenmental is unknown.");
            }

            Guid g = Guid.NewGuid();
            string key = g.ToString();
            string ret = "";
            cmd += " ID=" + key;
            cmd += Environment.NewLine;
            lock (supplemental.Waitings)
            {
                supplemental.Waitings.Add(new KeyValue(key, string.Empty));
            }
            int count = 0;
            while (supplemental.Waitings.FirstOrDefault(q => q._key == key)._value == string.Empty)
            {
                supplemental.PublishMessage(agvinfo, cmd);
                if (count == 0)
                {
                    Thread.Sleep(500);
                }
                else
                {
                    var milliseconds = Convert.ToInt32(ApplicationDomain.Instance.GetAppConfig(ApplicationGlobal.KEY_EAPSTATUSRETYING_AWAITTIME));
                    Thread.Sleep(milliseconds);
                }
                count++;
            }
            var reply = supplemental.Waitings.FirstOrDefault(q => q._key == key);
            ret = reply._value;
            lock (supplemental.Waitings)
            {
                supplemental.Waitings.Remove(reply);
            }
            return ret;
        }
    }
}
